//
//  DWDComposeViewController.swift
//  dwdWb
//
//  Created by Dengdwd on 15/10/18.
//  Copyright © 2015年 dwd. All rights reserved.
//

import UIKit
import SVProgressHUD

class DWDComposeViewController: UIViewController, UITextViewDelegate{
    private var picHeight:CGFloat = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setUpNav()
        setUpView()
        setUpToolbar()
        setUpPic()
        setUpNotify()
    }
    func setUpNotify() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "closeComposeBtn", name: "closeComposeBtn", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "requestError", name: "requestError", object: nil)
    }
    
    func closeComposeBtn() {
        SVProgressHUD.showInfoWithStatus("发送成功")

        sendBtn.enabled = true

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.cancel()
        }
        
        
    }
    func requestError() {
        SVProgressHUD.showErrorWithStatus("发送失败")
        
        sendBtn.enabled = true
    }
    func changeTextView() {
        textView.placeLabel.hidden = true
        self.navigationItem.rightBarButtonItem?.enabled = true
    }
    
    func changeToolbarFrame() {
    toolbar.y = SCREENH - 44
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if picHeight == 0 {
        textView.becomeFirstResponder()
        }
    }

    private func setUpPic() {
        addChildViewController(picController)
        view.insertSubview(picController.view, belowSubview: toolbar)
        picController.collectionView?.backgroundColor = UIColor.lightGrayColor()
        picController.view.frame = CGRect(x: 0, y: SCREENH, width: SCREENW, height: 0)
        
    }
    
    @objc private func emotitionSelect() {
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emotitionVc.view : nil

        textView.becomeFirstResponder()
    }
    
    @objc private func picSelect() {
        textView.resignFirstResponder()
        picHeight = SCREENH * 0.6
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.picController.view.h = self.picHeight
            self.picController.view.y = SCREENH - self.picHeight
        }
    }
    
    func keyboardChange(notify:NSNotification) {
        //UIKeyboardFrameEndUserInfoKey --> 表示键盘弹出的最终位置
        
        //拿着最终位置 就可以计算出来toolBar的y值
        
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey]! as! NSValue).CGRectValue()
        
        /// 取出动画执行的时间
        let number = (notify.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as! NSNumber).doubleValue
        
        //设置toolBar的y值
        UIView.animateWithDuration(number) { () -> Void in
            
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: 7)!)
            self.toolbar.y = rect.origin.y - self.toolbar.bounds.height
        }
    }
    private lazy var toolbar:UIToolbar = {
        let toolbar = UIToolbar()
        toolbar.frame = CGRect(x: 0, y: SCREENH - 44, width: SCREENW, height: 44)
        let imageSettings = [["imageName":"compose_toolbar_picture","action":"picSelect"],["imageName":"compose_emoticonbutton_background","action":"emotitionSelect"],["imageName":"compose_trendbutton_background","action":"picSelect"],["imageName":"compose_mentionbutton_background","action":"picSelect"],["imageName":"compose_add_background","action":"picSelect"]]
        var items = [UIBarButtonItem]()
        for dict in imageSettings {
            items.append(UIBarButtonItem.item(dict["imageName"]!, title: "", target: self, action: Selector(dict["action"]!)))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        return toolbar
        }()
    
    private func setUpToolbar() {
        self.view.addSubview(toolbar)
    }
    
    
    
    
    
    private func setUpNav() {
    self.navigationItem.leftBarButtonItem = UIBarButtonItem.item("", title: "取消", target: self, action: "cancel")
    
    self.navigationItem.titleView = titleView
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
    self.navigationItem.rightBarButtonItem?.enabled = false

    }
    private func setUpView() {
    textView.size = CGSize(width: SCREENW, height: SCREENH)
    view.addSubview(textView)
    }
    private lazy var textView: DWDTextView = {
        let textV = DWDTextView()
        textV.font = UIFont.systemFontOfSize(20)
        textV.placeHolder = "hehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehehe"
        textV.delegate = self
        textV.alwaysBounceVertical = true
        textV.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textV
        }()
    func textViewDidChange(textView: UITextView) {
        self.textView.placeLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()        
    }
    private lazy var sendBtn:UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: "sendMsg", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        btn.setTitle("发送", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.size = CGSize(width: 44, height: 30)
        return btn
        }()
    @objc private func sendMsg() {

        sendBtn.enabled = false
        let text = textView.imageAttributeText
        let image = picController.pics.last
        if image == nil {
        NetworkTools.sharedTools.updateText(text, image: nil)
        }else {
        NetworkTools.sharedTools.updateText(text, image: image)
        }
    }
    private lazy var titleView:UILabel = {
         let label = UILabel()
         label.numberOfLines = 0
         label.textAlignment = NSTextAlignment.Center
         if let nickName = UserAcount.loadUserData()?.name {
            let title = "发微博\n\(nickName)"
            let range = (title as NSString).rangeOfString(nickName)
            var attr = NSMutableAttributedString(string: title)
            attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: range)
            label.attributedText = attr
         }else{
            label.text = "发微博"
         }
         label.sizeToFit()
         return label
    }()
    
    @objc private func cancel() {
    textView.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    }
    private var picController:DWDPicSelectViewController = DWDPicSelectViewController()
    private lazy var emotitionVc:EmotitionViewController = EmotitionViewController( emotitionBlock: { [weak self] (emotition:Emotition) ->() in
        self?.textView.insertEmotition(emotition)
        })
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
